home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / share / hplip / base / logger.py < prev    next >
Text File  |  2009-10-09  |  18KB  |  533 lines

  1. # -*- coding: utf-8 -*-
  2. #
  3. # (c) Copyright 2002-2008 Hewlett-Packard Development Company, L.P.
  4. #
  5. # This program is free software; you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation; either version 2 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program; if not, write to the Free Software
  17. # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
  18. #
  19. # Authors: Doug Deprenger, Don Welch
  20. #
  21.  
  22. # Std Lib
  23. import sys
  24. import thread # TODO: Use threading instead (thread deprecated in Python 3.0)
  25. import syslog
  26. import traceback
  27. import string
  28. import os
  29. import re
  30. import pprint
  31.  
  32. identity = string.maketrans('','')
  33. unprintable = identity.translate(identity, string.printable)
  34.  
  35. def printable(s):
  36.     return s.translate(identity, unprintable)
  37.  
  38. DEFAULT_LOG_LEVEL = 'info'
  39.  
  40. class Logger(object):
  41.     LOG_LEVEL_NONE = 99
  42.     #LOG_LEVEL_INFO = 50
  43.     LOG_LEVEL_FATAL = 40
  44.     LOG_LEVEL_ERROR = 30
  45.     LOG_LEVEL_WARN = 20
  46.     LOG_LEVEL_INFO = 10
  47.     LOG_LEVEL_DEBUG3 = 3
  48.     LOG_LEVEL_DBG3 = 3
  49.     LOG_LEVEL_DEBUG2 = 2
  50.     LOG_LEVEL_DBG2 = 2
  51.     LOG_LEVEL_DEBUG = 1
  52.     LOG_LEVEL_DBG = 1
  53.  
  54.     logging_levels = {'none' : LOG_LEVEL_NONE,
  55.                        'fata' : LOG_LEVEL_FATAL,
  56.                        'fatal' : LOG_LEVEL_FATAL,
  57.                        'erro' : LOG_LEVEL_ERROR,
  58.                        'error' : LOG_LEVEL_ERROR,
  59.                        'warn' : LOG_LEVEL_WARN,
  60.                        'info' : LOG_LEVEL_INFO,
  61.                        'debug' : LOG_LEVEL_DEBUG,
  62.                        'dbg'  : LOG_LEVEL_DEBUG,
  63.                        'debug2' : LOG_LEVEL_DEBUG2,
  64.                        'dbg2' : LOG_LEVEL_DEBUG2,
  65.                        'debug3' : LOG_LEVEL_DEBUG3,
  66.                        'dbg3' : LOG_LEVEL_DEBUG3,
  67.                        }
  68.  
  69.     LOG_TO_DEV_NULL = 0
  70.     LOG_TO_CONSOLE = 1
  71.     LOG_TO_SCREEN = 1
  72.     LOG_TO_FILE = 2
  73.     LOG_TO_CONSOLE_AND_FILE = 3
  74.     LOG_TO_BOTH = 3
  75.  
  76.     # Copied from Gentoo Portage output.py
  77.     # Copyright 1998-2003 Daniel Robbins, Gentoo Technologies, Inc.
  78.     # Distributed under the GNU Public License v2
  79.     codes={}
  80.     codes["reset"]="\x1b[0m"
  81.     codes["bold"]="\x1b[01m"
  82.  
  83.     codes["teal"]="\x1b[36;06m"
  84.     codes["turquoise"]="\x1b[36;01m"
  85.  
  86.     codes["fuscia"]="\x1b[35;01m"
  87.     codes["purple"]="\x1b[35;06m"
  88.  
  89.     codes["blue"]="\x1b[34;01m"
  90.     codes["darkblue"]="\x1b[34;06m"
  91.  
  92.     codes["green"]="\x1b[32;01m"
  93.     codes["darkgreen"]="\x1b[32;06m"
  94.  
  95.     codes["yellow"]="\x1b[33;01m"
  96.     codes["brown"]="\x1b[33;06m"
  97.  
  98.     codes["red"]="\x1b[31;01m"
  99.     codes["darkred"]="\x1b[31;06m"
  100.  
  101.  
  102.     def __init__(self, module='', level=LOG_LEVEL_INFO, where=LOG_TO_CONSOLE_AND_FILE,
  103.                  log_datetime=False, log_file=None):
  104.  
  105.         self._where = where
  106.         self._log_file = log_file
  107.         self._log_file_f = None
  108.         self._log_datetime = log_datetime
  109.         self._lock = thread.allocate_lock()
  110.         self.module = module
  111.         self.pid = os.getpid()
  112.         self.fmt = True
  113.         self.set_level(level)
  114.  
  115.  
  116.     def set_level(self, level):
  117.         if isinstance(level, str):
  118.             level = level.lower()
  119.             if level in Logger.logging_levels.keys():
  120.                 self._level = Logger.logging_levels.get(level, Logger.LOG_LEVEL_INFO)
  121.                 return True
  122.             else:
  123.                 self.error("Invalid logging level: %s" % level)
  124.                 return False
  125.  
  126.         elif isinstance(level, int):
  127.             if Logger.LOG_LEVEL_DEBUG3 <= level <= Logger.LOG_LEVEL_FATAL:
  128.                 self._level = level
  129.             else:
  130.                 self._level = Logger.LOG_LEVEL_ERROR
  131.                 self.error("Invalid logging level: %d" % level)
  132.                 return False
  133.  
  134.         else:
  135.             return False
  136.  
  137.  
  138.     def set_module(self, module):
  139.         self.module = module
  140.         self.pid = os.getpid()
  141.  
  142.  
  143.     def no_formatting(self):
  144.         self.fmt = False
  145.  
  146.  
  147.     def set_logfile(self, log_file):
  148.         self._log_file = log_file
  149.         try:
  150.             self._log_file_f = file(self._log_file, 'w')
  151.         except IOError:
  152.             self._log_file = None
  153.             self._log_file_f = None
  154.             self._where = Logger.LOG_TO_SCREEN
  155.  
  156.  
  157.     def get_logfile(self):
  158.         return self._log_file
  159.  
  160.  
  161.     def set_where(self, where):
  162.         self._where = where
  163.  
  164.  
  165.     def get_level(self):
  166.         return self._level
  167.  
  168.  
  169.     def is_debug(self):
  170.         return self._level <= Logger.LOG_LEVEL_DEBUG3
  171.  
  172.     level = property(get_level, set_level)
  173.  
  174.  
  175.     def log(self, message, level, newline=True):
  176.         if self._level <= level:
  177.             if self._where in (Logger.LOG_TO_CONSOLE, Logger.LOG_TO_CONSOLE_AND_FILE):
  178.                 try:
  179.                     self._lock.acquire()
  180.                     if level >= Logger.LOG_LEVEL_WARN:
  181.                         out = sys.stderr
  182.                     else:
  183.                         out = sys.stdout
  184.  
  185.                     try:
  186.                         out.write(message)
  187.                     except UnicodeEncodeError:
  188.                         out.write(message.encode("utf-8"))
  189.  
  190.                     if newline:
  191.                         out.write('\n')
  192.  
  193.                 finally:
  194.                     self._lock.release()
  195.  
  196.  
  197.     def log_to_file(self, message):
  198.         if self._log_file_f is not None:
  199.             try:
  200.                 self._lock.acquire()
  201.                 self._log_file_f.write(message.replace('\x1b', ''))
  202.                 self._log_file_f.write('\n')
  203.  
  204.             finally:
  205.                 self._lock.release()
  206.  
  207.  
  208.     def stderr(self, message):
  209.         try:
  210.             self._lock.acquire()
  211.             sys.stderr.write("%s: %s\n" % (self.module, message))
  212.         finally:
  213.             self._lock.release()
  214.  
  215.  
  216.     def debug(self, message):
  217.         if self._level <= Logger.LOG_LEVEL_DEBUG:
  218.             txt = "%s[%d]: debug: %s" % (self.module, self.pid, message)
  219.             self.log(self.color(txt, 'blue'), Logger.LOG_LEVEL_DEBUG)
  220.  
  221.             if self._log_file is not None and \
  222.                 self._where in (Logger.LOG_TO_FILE, Logger.LOG_TO_CONSOLE_AND_FILE):
  223.                 self.log_to_file(txt)
  224.  
  225.     dbg = debug
  226.  
  227.     def debug2(self, message):
  228.         if self._level <= Logger.LOG_LEVEL_DEBUG2:
  229.             txt = "%s[%d]: debug2: %s" % (self.module, self.pid, message)
  230.             self.log(self.color(txt, 'blue'), Logger.LOG_LEVEL_DEBUG2)
  231.  
  232.             if self._log_file is not None and \
  233.                 self._where in (Logger.LOG_TO_FILE, Logger.LOG_TO_CONSOLE_AND_FILE):
  234.                 self.log_to_file(txt)
  235.     dbg2 = debug2
  236.  
  237.     def debug3(self, message):
  238.         if self._level <= Logger.LOG_LEVEL_DEBUG3:
  239.             txt = "%s[%d]: debug3: %s" % (self.module, self.pid, message)
  240.             self.log(self.color(txt, 'blue'), Logger.LOG_LEVEL_DEBUG3)
  241.  
  242.             if self._log_file is not None and \
  243.                 self._where in (Logger.LOG_TO_FILE, Logger.LOG_TO_CONSOLE_AND_FILE):
  244.                 self.log_to_file(txt)
  245.     dbg3 = debug3
  246.  
  247.  
  248.     def debug_block(self, title, block):
  249.         if self._level <= Logger.LOG_LEVEL_DEBUG:
  250.             line = "%s[%d]: debug: %s:" % (self.module,  self.pid, title)
  251.             self.log(self.color(line, 'blue'), Logger.LOG_LEVEL_DEBUG)
  252.             self.log(self.color(block, 'blue'), Logger.LOG_LEVEL_DEBUG)
  253.  
  254.             if self._log_file is not None and \
  255.                 self._where in (Logger.LOG_TO_FILE, Logger.LOG_TO_CONSOLE_AND_FILE):
  256.  
  257.                 self.log_to_file(line % (self.module, self.pid, title))
  258.                 self.log_to_file(block)
  259.  
  260.  
  261.     printable = """ !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~  """
  262.  
  263.     def log_data(self, data, width=16):
  264.         if self._level <= Logger.LOG_LEVEL_DEBUG:
  265.             if data:
  266.                 index, line = 0, data[0:width]
  267.                 while line:
  268.                     txt = ' '.join(['%04x: ' % index, ' '.join(['%02x' % ord(d) for d in line]),
  269.                         ' '*(width*3-3*len(line)), ''.join([('.', i)[i in Logger.printable] for i in line])])
  270.  
  271.                     self.log(self.color("%s[%d]: debug: %s" % (self.module,  self.pid, txt), 'blue'),
  272.                         Logger.LOG_LEVEL_DEBUG)
  273.  
  274.                     index += width
  275.                     line = data[index:index+width]
  276.             else:
  277.                 self.log(self.color("%s[%d]: debug: %s" % (self.module,  self.pid, "0000: (no data)"), 'blue'),
  278.                         Logger.LOG_LEVEL_DEBUG)
  279.  
  280.  
  281.     def info(self, message=''):
  282.         if self._level <= Logger.LOG_LEVEL_INFO:
  283.             self.log(message, Logger.LOG_LEVEL_INFO)
  284.  
  285.             if self._log_file is not None and \
  286.                 self._where in (Logger.LOG_TO_FILE, Logger.LOG_TO_CONSOLE_AND_FILE):
  287.                 self.log_to_file("%s[%d]: info: :%s" % (self.module, self.pid, message))
  288.  
  289.     information = info
  290.  
  291.  
  292.     def warn(self, message):
  293.         if self._level <= Logger.LOG_LEVEL_WARN:
  294.             txt = "warning: %s" % message.encode('utf-8')
  295.             self.log(self.color(txt, 'fuscia'), Logger.LOG_LEVEL_WARN)
  296.  
  297.             syslog.syslog(syslog.LOG_WARNING, "%s[%d]: %s" % (self.module, self.pid, txt))
  298.  
  299.             if self._log_file is not None and \
  300.                 self._where in (Logger.LOG_TO_FILE, Logger.LOG_TO_CONSOLE_AND_FILE):
  301.                 self.log_to_file(txt)
  302.  
  303.     warning = warn
  304.  
  305.  
  306.     def note(self, message):
  307.         if self._level <= Logger.LOG_LEVEL_WARN:
  308.             txt = "note: %s" % message
  309.             self.log(self.color(txt, 'green'), Logger.LOG_LEVEL_WARN)
  310.  
  311.             if self._log_file is not None and \
  312.                 self._where in (Logger.LOG_TO_FILE, Logger.LOG_TO_CONSOLE_AND_FILE):
  313.                 self.log_to_file(txt)
  314.  
  315.     notice = note
  316.  
  317.  
  318.     def error(self, message):
  319.         if self._level <= Logger.LOG_LEVEL_ERROR:
  320.             txt = "error: %s" % message.encode("utf-8")
  321.             self.log(self.color(txt, 'red'), Logger.LOG_LEVEL_ERROR)
  322.  
  323.             syslog.syslog(syslog.LOG_ALERT, "%s[%d]: %s" % (self.module, self.pid, txt))
  324.  
  325.             if self._log_file is not None and \
  326.                 self._where in (Logger.LOG_TO_FILE, Logger.LOG_TO_CONSOLE_AND_FILE):
  327.                 self.log_to_file(txt)
  328.  
  329.  
  330.     def fatal(self, message):
  331.         if self._level <= Logger.LOG_LEVEL_FATAL:
  332.             txt = "fatal error: :%s" % self.module.encode('utf-8')
  333.             self.log(self.color(txt, 'red'), Logger.LOG_LEVEL_DEBUG)
  334.  
  335.             syslog.syslog(syslog.LOG_ALERT, "%s[%d]: %s" % (self.module, self.pid, txt))
  336.  
  337.             if self._log_file is not None and \
  338.                 self._where in (Logger.LOG_TO_FILE, Logger.LOG_TO_CONSOLE_AND_FILE):
  339.                 self.log_to_file(txt)
  340.  
  341.  
  342.     def exception(self):
  343.         typ, value, tb = sys.exc_info()
  344.         body = "Traceback (innermost last):\n"
  345.         lst = traceback.format_tb(tb) + traceback.format_exception_only(typ, value)
  346.         body = body + "%-20s %s" % (''.join(lst[:-1]), lst[-1],)
  347.         self.fatal(body)
  348.  
  349.  
  350.     def color(self, text, color):
  351.         if self.fmt:
  352.             return ''.join([Logger.codes.get(color, 'bold'), text, Logger.codes['reset']])
  353.         return text
  354.  
  355.  
  356.     def bold(self, text):
  357.         return self.color(text, 'bold')
  358.  
  359.  
  360.     def red(self, text):
  361.         return self.color(text, 'red')
  362.  
  363.  
  364.     def green(self, text):
  365.         return self.color(text, 'green')
  366.  
  367.  
  368.     def purple(self, text):
  369.         return self.color(text, 'purple')
  370.  
  371.  
  372.     def yellow(self, text):
  373.         return self.color(text, 'yellow')
  374.  
  375.  
  376.     def darkgreen(self, text):
  377.         return self.color(text, 'darkgreen')
  378.  
  379.  
  380.     def blue(self, text):
  381.         return self.color(text, 'blue')
  382.  
  383.     """Pretty print an XML document.
  384.  
  385.     LICENCE:
  386.     Copyright (c) 2008, Fredrik Ekholdt
  387.     All rights reserved.
  388.  
  389.     Redistribution and use in source and binary forms, with or without
  390.     modification, are permitted provided that the following conditions are met:
  391.  
  392.     * Redistributions of source code must retain the above copyright notice,
  393.     this list of conditions and the following disclaimer.
  394.  
  395.     * Redistributions in binary form must reproduce the above copyright notice,
  396.     this list of conditions and the following disclaimer in the documentation
  397.     and/or other materials provided with the distribution.
  398.  
  399.     * Neither the name of None nor the names of its contributors may be used to
  400.     endorse or promote products derived from this software without specific prior
  401.     written permission.
  402.  
  403.     THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  404.     AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  405.     IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  406.     ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  407.     LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  408.     CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  409.     SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  410.     INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  411.     CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  412.     ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  413.     POSSIBILITY OF SUCH DAMAGE."""
  414.  
  415.     def _pprint_line(self, indent_level, line, width=100, level=LOG_LEVEL_DEBUG):
  416.         if line.strip():
  417.             start = ""
  418.             number_chars = 0
  419.             for l in range(indent_level):
  420.                 start = start + " "
  421.                 number_chars = number_chars + 1
  422.             try:
  423.                 elem_start = re.findall("(\<\W{0,1}\w+) ?", line)[0]
  424.                 elem_finished = re.findall("([?|\]\]]*\>)", line)[0]
  425.                 #should not have *
  426.                 attrs = re.findall("(\S*?\=\".*?\")", line)
  427.                 #output.write(start + elem_start)
  428.                 self.log(start+elem_start, level, False)
  429.                 number_chars = len(start + elem_start)
  430.                 for attr in attrs:
  431.                     if (attrs.index(attr) + 1) == len(attrs):
  432.                         number_chars = number_chars + len(elem_finished)
  433.  
  434.                     if (number_chars + len(attr) + 1) > width:
  435.                         #output.write("\n")
  436.                         self.log("\n", level, False)
  437.                         #for i in range(len(start + elem_start) + 1):
  438.                             ##output.write(" ")
  439.                             #self.log(" ", level, False)
  440.                         self.log(" "*(len(start + elem_start) + 1), level, False)
  441.                         number_chars = len(start + elem_start) + 1
  442.  
  443.                     else:
  444.                         #output.write(" ")
  445.                         self.log(" ", level, False)
  446.                         number_chars = number_chars + 1
  447.                     #output.write(attr)
  448.                     self.log(attr, level, False)
  449.                     number_chars = number_chars + len(attr)
  450.                 #output.write(elem_finished + "\n")
  451.                 self.log(elem_finished + "\n", level, False)
  452.  
  453.             except IndexError:
  454.                 #give up pretty print this line
  455.                 #output.write(start + line + "\n")
  456.                 self.log(start + line + "\n", level, False)
  457.  
  458.  
  459.     def _pprint_elem_content(self, indent_level, line, level=LOG_LEVEL_DEBUG):
  460.         if line.strip():
  461.             #for l in range(indent_level):
  462.                 ##output.write(" ")
  463.                 #self.log(" ", level, False)
  464.             self.log(" "*indent_level, level, False)
  465.  
  466.             #output.write(line + "\n")
  467.             self.log(line + "\n", level, False)
  468.  
  469.  
  470.     def _get_next_elem(self, data):
  471.         start_pos = data.find("<")
  472.         end_pos = data.find(">") + 1
  473.         retval = data[start_pos:end_pos]
  474.         stopper = retval.rfind("/")
  475.         if stopper < retval.rfind("\""):
  476.             stopper = -1
  477.  
  478.         single = (stopper > -1 and ((retval.find(">") - stopper) < (stopper - retval.find("<"))))
  479.  
  480.         ignore_excl = retval.find("<!") > -1
  481.         ignore_question =  retval.find("<?") > -1
  482.  
  483.         if ignore_excl:
  484.             cdata = retval.find("<![CDATA[") > -1
  485.             if cdata:
  486.                 end_pos = data.find("]]>")
  487.                 if end_pos > -1:
  488.                     end_pos = end_pos + len("]]>")
  489.  
  490.         elif ignore_question:
  491.             end_pos = data.find("?>") + len("?>")
  492.  
  493.         ignore = ignore_excl or ignore_question
  494.  
  495.         no_indent = ignore or single
  496.  
  497.         #print retval, end_pos, start_pos, stopper > -1, no_indent
  498.         return start_pos, \
  499.             end_pos, \
  500.             stopper > -1, \
  501.             no_indent
  502.  
  503.  
  504.     def xml(self, xml, level=LOG_LEVEL_DEBUG, indent=4, width=80):
  505.         """Pretty print xml.
  506.         Use indent to select indentation level. Default is 4   """
  507.         data = xml
  508.         indent_level = 0
  509.         start_pos, end_pos, is_stop, no_indent  = self._get_next_elem(data)
  510.         while ((start_pos > -1 and end_pos > -1)):
  511.             self._pprint_elem_content(indent_level, data[:start_pos].strip(), level=level)
  512.             data = data[start_pos:]
  513.             if is_stop and not no_indent:
  514.                 indent_level = indent_level - indent
  515.  
  516.             self._pprint_line(indent_level,
  517.                         data[:end_pos - start_pos],
  518.                         width=width, level=level)
  519.  
  520.             data = data[end_pos - start_pos:]
  521.             if not is_stop and not no_indent :
  522.                 indent_level = indent_level + indent
  523.  
  524.             if not data:
  525.                 break
  526.             else:
  527.                 start_pos, end_pos, is_stop, no_indent  = self._get_next_elem(data)
  528.  
  529.     # END: Pretty print an XML document.
  530.  
  531.  
  532.     def pprint(self, data):
  533.         self.info(pprint.pformat(data))